package com.kingtone.rongji;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.kingtone.rongji.biz.Product;
import com.kingtone.rongji.tool.AppRestClient;
import com.kingtone.rongji.tool.CartUtils;
import com.kingtone.rongji.tool.RongJiRestClient;
import com.kingtone.rongji.tool.RongJiUtils;
import com.kingtone.rongji.ui.VerticalViewPager;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;

public class YuShouActivity extends BaseActivity implements OnPageChangeListener,OnClickListener {

	private static final String tag = YuShouActivity.class.getSimpleName();
	
	private TextView mContent;
	private TextView mDetailLink;
	private TextView mMoney;
	private TextView mOldMoney;
	private Button   mOrderLink;
	
	private DummyAdapter mAdapter;
	
	private static DisplayImageOptions mOptions;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_yushou);
		
		mOptions = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true)
				.bitmapConfig(Bitmap.Config.RGB_565).delayBeforeLoading(100).showImageOnLoading(R.drawable.product_no_img).showImageOnFail(R.drawable.product_no_img).build();
		
		((TextView) findViewById(R.id.title)).setText("新品预售");
		
		findViewById(R.id.back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		
		mAdapter = new DummyAdapter(getFragmentManager());
		VerticalViewPager verticalViewPager = (VerticalViewPager) findViewById(R.id.verticalviewpager);
        verticalViewPager.setAdapter(mAdapter);
        verticalViewPager.setOnPageChangeListener(this);
        
        mContent = (TextView) findViewById(R.id.content);
        mDetailLink = (TextView) findViewById(R.id.detail_link);
        mMoney = (TextView) findViewById(R.id.money);
        mOldMoney = (TextView) findViewById(R.id.old_money);
        mOrderLink = (Button) findViewById(R.id.order_link);
        
        mDetailLink.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        mOldMoney.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        
        mDetailLink.setOnClickListener(this);
        mOrderLink.setOnClickListener(this);
        
        initData();
	}
	
	
	private void initData() {
		RongJiRestClient.getYuShou(new AsyncHttpResponseHandler() {
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				if(arg0==200) {
					try {
						String responseText = new String(arg2);
						Log.d(tag, "Result:" + responseText);
						
						Gson gson = new Gson();
						JsonParser parser = new JsonParser();
						JsonObject jObj = parser.parse(responseText).getAsJsonObject();
						JsonArray array = jObj.getAsJsonArray("Data");
						List<Product> list = new ArrayList<Product>();
						for(JsonElement obj:array) {
							Product object = gson.fromJson(obj, Product.class);
							
							// 处理图片地址
							if(!TextUtils.isEmpty(object.getTSImageSet()) && object.getTSImageSet().indexOf(',')>0) {
								String[] arrStr = object.getTSImageSet().split(",");
								object.setTSImageSet(arrStr[0]);
							}
							
							list.add(object);
						}
						
						mAdapter.setDatas(list);
						
						onPageSelected(0);
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					Log.e(tag, "Error:code=" + arg0);
				}
			}
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
				Log.e(tag, "Failed:code=" + arg0);
				if(null != arg3) {
					arg3.printStackTrace();
				}
			}
		});
	}


	public class DummyAdapter extends FragmentPagerAdapter {

		private List<Product> datas = new ArrayList<Product>();
		
        public DummyAdapter(FragmentManager fm) {
            super(fm);
        }
        
        public void setDatas(List<Product> datas) {
        	this.datas.clear();
        	this.datas.addAll(datas);
        	notifyDataSetChanged();
        }
        
        public List<Product> getDatas() {
        	return this.datas;
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(datas.get(position));
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return "PAGE" + position;
        }

    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_ITEM = "item";
        
        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(Product product) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putSerializable(ARG_SECTION_ITEM, product);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
        	View rootView = inflater.inflate(R.layout.fragment_yushou, container, false);
        	Product item = (Product) getArguments().getSerializable(ARG_SECTION_ITEM);
        	if(null != item) {
        		//TextView textView = (TextView) rootView.findViewById(R.id.textview);
        		//textView.setText(item.getProductName());
        		final ImageView imageView = (ImageView) rootView.findViewById(R.id.imageview);
        		
        		if(!TextUtils.isEmpty(item.getTSImageSet())) {
        			String iurl = AppRestClient.convertImageUrl(item.getProductId(), item.getTSImageSet());
        			ImageLoader.getInstance().displayImage(iurl, imageView, mOptions, new ImageLoadingListener() {
						
						@Override
						public void onLoadingStarted(String arg0, View arg1) {
							imageView.setScaleType(ScaleType.CENTER);
						}
						
						@Override
						public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
							imageView.setScaleType(ScaleType.CENTER);
						}
						
						@Override
						public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
							imageView.setScaleType(ScaleType.CENTER_CROP);
						}
						
						@Override
						public void onLoadingCancelled(String arg0, View arg1) {
							imageView.setScaleType(ScaleType.CENTER);
						}
					});
        		}
        	}
            return rootView;
        }


    }

	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int arg0) {
		if(null != mAdapter.getDatas() && mAdapter.getDatas().size()>0) {
			Product item = mAdapter.getDatas().get(arg0);
			if(null != item) {
				// 设置浮层内容
				mContent.setText(item.getTitle());
				mOldMoney.setText("市场价 ￥" + RongJiUtils.formatCost(item.getMarketPrice()));
				mMoney.setText("￥" + RongJiUtils.formatCost(item.getUnitPrice()));
				
				mDetailLink.setTag(item);
				mOrderLink.setTag(item);
			}
		}
	}


	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.detail_link:
			Product item = (Product) mDetailLink.getTag();
			if(null!=item) {
				Intent intent = new Intent(YuShouActivity.this, ProductDetailActivity.class);
				intent.putExtra("productId", item.getProductId());
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
			}
			break;
		case R.id.order_link:
			Product item2 = (Product) mOrderLink.getTag();
			if(null!=item2) {
				CartUtils.add2Cart(YuShouActivity.this, item2);
				Intent intent = new Intent(YuShouActivity.this, CartActivity.class);
				startActivity(intent);
			}
			break;
		default:
			break;
		}
		
	}
	
}
